package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.RoomAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Room;
import com.dotstone.chipism.listener.UpdateDataListener;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class GroupListActivity extends BaseActivity {
	private TextView tv_statusBar_mian;
	private LinearLayout mBackL;
	private Button mBackB;
	private ListView mRoomLv;
	private Button mAddgroupB;
	private static final int GET_ROOM_SUCCESS = 0;
	private List<Room> mRooms = new ArrayList<Room>();
	private RoomAdapter mAdapter;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private NormalDialog mNormalDialog;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.add_btn:
			BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(GroupListActivity.this, GroupEditActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					intent.putExtra("position", -1);
					startActivity(intent);
				}
			});
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 4:
				// if (mAdapter == null) {
				// mAdapter = new RoomAdapter(getApplicationContext(), mRooms);
				// mRoomLv.setAdapter(mAdapter);
				// } else {
				// mAdapter.notifyDataSetChanged();
				// }
				initData();
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_group_list;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		BlurBehind.getInstance()
				// .withAlpha(80)
				// .withFilterColor(Color.parseColor("#000000"))
				.setBackground(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		boolVersion();
		mBackL = $(R.id.back_layout);
		mBackL.setVisibility(View.GONE);
		mBackB = $(R.id.back_btn);
		mBackB.setVisibility(View.VISIBLE);
		mRoomLv = $(R.id.room_lv);
		mAddgroupB = $(R.id.add_btn);
		mBackB.setOnClickListener(this);
		mAddgroupB.setOnClickListener(this);
		mRoomLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
				// TODO Auto-generated method stub
				BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
					@Override
					public void onBlurComplete() {
						Intent intent = new Intent(GroupListActivity.this, GroupEditActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						intent.putExtra("position", position);
						startActivity(intent);
					}
				});
			}
		});
		mRoomLv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View v, final int p, long arg3) {
				// TODO Auto-generated method stub

				mNormalDialog = new NormalDialog(GroupListActivity.this);
				mNormalDialog.content("是否删除该组别：" + mRooms.get(p).getRoomName() + "？").style(NormalDialog.STYLE_TWO)//
						.titleTextSize(18)//
						.showAnim(bas_in)//
						.dismissAnim(bas_out)//
						.show();
				mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
					}
				}, new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
						deleteRoom(mRooms.get(p).getRoomId());
					}
				});
				return true;
			}
		});

	}

	private void deleteRoom(String id) {

		if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
			ToastShow.Show(getApplicationContext(), "没有网络");
			return;
		}

		RequestParams params = new RequestParams(HttpURL.DELETE_ROOM_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("roomId", id);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				// Log.e("test", "delete =" + result);
				// deleteLocal();
				try {
					JSONObject jsonObject = new JSONObject(result);
					String resultCode = jsonObject.getString("resultCode");
					if (resultCode.equals("1")) {
						ToastShow.Show(getApplicationContext(), "删除成功");
						// SocketClientManager.getInstance().mSocketMap.remove(mDevices.get(position).getDeviceAddress());
						getAllRooms();
					} else {
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
					// deleteLocal();
					ToastShow.Show(getApplicationContext(), "删除失败，请稍后再试");
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}
		});
	}

	public void getAllRooms() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_ROOM_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all rooms = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					DeviceManager.getInstance().clearRoom();
					Log.e("wmy", "get all =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String roomId = jo.getString("roomId");
									String roomName = jo.optString("roomName");
									List<Device> deviceses = new ArrayList<Device>();
									JSONArray ja = jo.getJSONArray("deviceses");
									for (int j = 0; j < ja.length(); j++) {
										int deviceType = ja.getJSONObject(j).getInt("deviceType");
										String deviceId = ja.getJSONObject(j).getString("deviceId");// deviceName
										String deviceMac = ja.getJSONObject(j).optString("deviceMac");
										Log.i("wmy", "group deviceMac = " + deviceMac);
										int status = ja.getJSONObject(j).getInt("nurdStatus");
										String deviceName = ja.getJSONObject(j).getString("remarks");
										Log.i("wmy", "group device = " + deviceName);
										Device device = new Device(deviceId, deviceMac, deviceName, deviceType, status);
										Log.i("wmy", "添加一个device" + deviceName);
										deviceses.add(device);
									}
									Room room = new Room(roomId, roomName, deviceses);
									DeviceManager.getInstance().setGroupChildDevices(roomId, deviceses);
									DeviceManager.getInstance().addRoom(room);
								}
							}
							Log.i("wmy", "准备发送消息");
							Message msg = Message.obtain();
							msg.what = 4;
							mHandler.sendMessage(msg);
							Log.i("wmy", "已发送消息");
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
//							ToastShow.Show(getApplicationContext(), "您的登陆已超时，请重新登陆");
//							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
//							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// getAllRooms();
		// initData();
		getAllRooms();
		SocketManager.getInstance().setOnUpdateDataListener(new UpdateDataListener() {

			@Override
			public void onUpdate() {
				// TODO Auto-generated method stub
				getAllRooms();
			}
		});
	}

	private void initData() {
		mRooms = DeviceManager.getInstance().getRooms();
		if (mAdapter == null) {
			mAdapter = new RoomAdapter(getApplicationContext(), mRooms);
			mRoomLv.setAdapter(mAdapter);
		} else {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

}
